package com.ruoyi.car.business.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.ruoyi.car.business.domain.BusAppointment;
import com.ruoyi.car.business.domain.BusStatement;
import com.ruoyi.car.business.domain.BusStatementItem;
import com.ruoyi.car.business.mapper.BusStatementItemMapper;
import com.ruoyi.car.business.query.StatementItemQuery;
import com.ruoyi.car.business.service.IBusAppointmentService;
import com.ruoyi.car.business.service.IBusStatementItemService;
import com.ruoyi.car.business.service.IBusStatementService;
import com.ruoyi.common.exception.business.BusinessException;
import com.ruoyi.common.utils.ShiroUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 结算单明细Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-01-29
 */
@Service
public class BusStatementItemServiceImpl implements IBusStatementItemService
{
    @Autowired
    private BusStatementItemMapper busStatementItemMapper;
    @Autowired
    private IBusStatementService statementService;
    @Autowired
    private IBusAppointmentService appointmentService;

    /**
     * 查询结算单明细
     * 
     * @param id 结算单明细主键
     * @return 结算单明细
     */
    @Override
    public BusStatementItem selectBusStatementItemById(Long id)
    {
        return busStatementItemMapper.selectBusStatementItemById(id);
    }

    /**
     * 查询结算单明细列表
     * 
     * @param busStatementItem 结算单明细
     * @return 结算单明细
     */
    @Override
    public List<BusStatementItem> selectBusStatementItemList(BusStatementItem busStatementItem)
    {
        return busStatementItemMapper.selectBusStatementItemList(busStatementItem);
    }

    /**
     * 新增结算单明细
     * 
     * @param busStatementItem 结算单明细
     * @return 结果
     */
    @Override
    public int insertBusStatementItem(BusStatementItem busStatementItem)
    {
        return busStatementItemMapper.insertBusStatementItem(busStatementItem);
    }

    /**
     * 修改结算单明细
     * 
     * @param busStatementItem 结算单明细
     * @return 结果
     */
    @Override
    public int updateBusStatementItem(BusStatementItem busStatementItem)
    {
        return busStatementItemMapper.updateBusStatementItem(busStatementItem);
    }

    /**
     * 批量删除结算单明细
     * 
     * @param ids 需要删除的结算单明细主键
     * @return 结果
     */
    @Override
    public int deleteBusStatementItemByIds(String ids)
    {
        return busStatementItemMapper.deleteBusStatementItemByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除结算单明细信息
     * 
     * @param id 结算单明细主键
     * @return 结果
     */
    @Override
    public int deleteBusStatementItemById(Long id)
    {
        return busStatementItemMapper.deleteBusStatementItemById(id);
    }

    @Override
    public List query(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return busStatementItemMapper.query(qo);
    }

    @Override
    @Transactional
    public void saveItems(List<BusStatementItem> items) {
        // 进行合理性校验
        if (items == null || items.size() <= 0) {
            throw new BusinessException("非法操作");
        }
        BusStatementItem tempItem = items.remove(items.size() - 1);
        Long statementId = tempItem.getStatementId();
        BigDecimal disCountPrice = tempItem.getItemPrice();
        BusStatement statement = statementService.selectBusStatementById(statementId);
        if (BusStatement.STATUS_PAID.equals(statement.getStatus())) {
            throw new BusinessException("已支付的结算不能进行保存操作");
        }
        // 删除之前的明细的数据
        busStatementItemMapper.deleteByStatementId(statementId);
        BigDecimal totalAmount = new BigDecimal(0);
        BigDecimal totalQuantity = new BigDecimal(0);
        for (BusStatementItem item : items) {
            // 保存数据库中
            busStatementItemMapper.insertBusStatementItem(item);
            totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
            totalQuantity = totalQuantity.add(item.getItemQuantity());
        }
        // disCountPrice - totalAmount > 0
        if (disCountPrice.compareTo(totalAmount) > 0) {
            throw new BusinessException("非法操作");
        }
        // 更新结算单的总消费金额,总数量,总折扣金额
        statementService.updateAmount(statementId, totalAmount, totalQuantity, disCountPrice);
    }

    @Override
    public void pay(Long statementId) {
        Long userId = ShiroUtils.getUserId();
        // 修改结算单状态
        statementService.pay(statementId, userId, BusStatement.STATUS_PAID);
        // 判断当前结算单是否有对应预约单,如果有修改状态
        BusStatement statement = statementService.selectBusStatementById(statementId);
        if (statement.getAppointmentId() != null) {
            appointmentService.changeStatus(statement.getAppointmentId(), BusAppointment.STATUS_PAID);
        }
    }

    @Override
    public Workbook exportOP(Long statementId) {
        BusStatement statement = statementService.selectBusStatementById(statementId);
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("结算明细");
        // 定义标题头
        Row titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("客户姓名");
        titleRow.createCell(1).setCellValue("联系方式");
        titleRow.createCell(2).setCellValue("车牌号码");
        titleRow.createCell(3).setCellValue("汽车类型");
        titleRow.createCell(4).setCellValue("服务类型");
        titleRow.createCell(5).setCellValue("到店时间");
        titleRow.createCell(6).setCellValue("总消费金额");
        titleRow.createCell(7).setCellValue("实付价格");
        titleRow.createCell(8).setCellValue("优惠价格");
        titleRow.createCell(9).setCellValue("服务项名称");
        titleRow.createCell(10).setCellValue("服务项价格");
        titleRow.createCell(11).setCellValue("购买数量");
        // 封装数据
        List<BusStatementItem> statementItemList = busStatementItemMapper.get(statementId);
        for (int i = 0; i < statementItemList.size(); i++) {
            Row row = sheet.createRow(i + 1);
            if (i == 0) {
                row.createCell(0).setCellValue(statement.getCustomerName());
                row.createCell(1).setCellValue(statement.getCustomerPhone());
                row.createCell(2).setCellValue(statement.getLicensePlate());
                row.createCell(3).setCellValue(statement.getCarSeries());
                row.createCell(4).setCellValue(statement.getServiceType() == 1 ? "保养" : "维修");
                row.createCell(5).setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(statement.getActualArrivalTime()));
                row.createCell(6).setCellValue(statement.getTotalAmount().toString());
                row.createCell(7).setCellValue(statement.getTotalAmount().subtract(statement.getDiscountAmount()).toString());
                row.createCell(8).setCellValue(statement.getDiscountAmount().toString());
            }
            BusStatementItem statementItem = statementItemList.get(i);
            row.createCell(9).setCellValue(statementItem.getItemName());
            row.createCell(10).setCellValue(statementItem.getItemPrice().toString());
            row.createCell(11).setCellValue(statementItem.getItemQuantity().toString());
        }
        return wb;
    }
}
